package handler

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"microdemo/restful/bff/internal/logic"
	"microdemo/restful/bff/internal/svc"
	"microdemo/restful/bff/internal/types"
	"net/http"
	"time"
)

type JwtHandler struct {
}

func NewJwtHandler() *JwtHandler {
	return &JwtHandler{}
}

func (jwt *JwtHandler) Login(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 打印 User-Agent 信息，用于验证路由中间件作用范围
		logx.Info(fmt.Sprintf("User-Agent 为：%s", r.Header.Get("User-Agent")))
		// 验证用户信息
		var req types.LoginRequest
		response := NewResponse()
		if err := httpx.Parse(r, &req); err != nil {
			// 自定义统一响应的处理函数
			response.Error(r.Context(), w, err)
			return
		}
		jwtLogic := logic.NewJwtLogic()
		err := jwtLogic.CheckUserInfo(&req)
		if err != nil {
			// 自定义统一响应的处理函数
			response.Error(r.Context(), w, err)
			return
		}
		// 拉取配置信息
		auth := svcCtx.Config.Auth
		// 生成 token
		token, err := jwtLogic.GetToken(auth.AccessSecret, time.Now().Unix(), auth.AccessExpire, "{userId: 100}")
		// 自定义统一响应的处理函数
		response.Result(r.Context(), w, token, err)
	}
}

func (jwt *JwtHandler) NeedJwt() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		httpx.OkJsonCtx(r.Context(), w, "测试需要 Jwt")
	}
}
